#include "mainwidget.h"
#include "util.h"
#include <QEvent>

MainWidget::MainWidget(QWidget *parent) : QWidget(parent)
{
    this->setMinimumSize(400,300);

    welcome_label = new QLabel();
    setting_button = new QPushButton();
    ok_button = new QPushButton();
    cancel_button = new QPushButton();
    setting_diaog = new SettingDialog();

    QHBoxLayout * button_layout = new QHBoxLayout();
    button_layout->addStretch();;
    button_layout->addWidget(setting_button);
    button_layout->addWidget(ok_button);
    button_layout->addWidget(cancel_button);
    button_layout->setSpacing(10);
    button_layout->setContentsMargins(0,0,0,0);

    QVBoxLayout *main_layout = new QVBoxLayout();
    main_layout->addWidget(welcome_label,0,Qt::AlignCenter);
    main_layout->addLayout(button_layout);
    main_layout->setSpacing(10);
    main_layout->setContentsMargins(10,10,10,10);

    this->setLayout(main_layout);
    this->translateUI();

    connect(setting_button,&QPushButton::clicked,
            this,&MainWidget::showSetting);
    connect(setting_diaog,&SettingDialog::switchLanguage,
            this,&MainWidget::switchLanguage);
}

void MainWidget::translateUI()
{
    this->setWindowTitle(tr("main widget"));
    welcome_label->setText(tr("welcome to Qt") +
                           QString("12345/67890"));
    setting_button->setText(tr("setting"));
    ok_button->setText(tr("ok"));
    cancel_button->setText(tr("cancel"));
}

void MainWidget::setLanguage(LANGUAGE current_language)
{
    this->current_language = current_language;
}

void MainWidget::changeEvent(QEvent *event)
{
    switch (event->type()) {
    case QEvent::LanguageChange :
        translateUI();
        break;
    default:
        QWidget::changeEvent(event);
        break;
    }
}

void MainWidget::setTranslator(QTranslator *translator)
{
    this->translate = translator;
}

void MainWidget::switchLanguage(LANGUAGE language)
{
    QString language_qm;
    switch (language) {
    case UI_ZH:
        language = UI_ZH;
        language_qm = QString(":/qm/main_widget_zh");
        break;
    case UI_EN:
        language = UI_EN;
        language_qm = QString(":/qm/main_widget_en");
        break;
    default:
        language = UI_ZH;
        language_qm = QString(":/qm/main_widget_zh");
        break;
    }

    qDebug() << language_qm;

    if (current_language != language) {
        current_language = language;
        translate->load(language_qm);
        Util::writeInit(QString("./user.ini"),
                        QString("language"),
                        QString::number(language,10));
    }
}

void MainWidget::showSetting()
{
    setting_diaog->loadConfig();
    setting_diaog->exec();
}











